﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Google.Apis.Customsearch.v1;
using Google.Apis.Customsearch.v1.Data;

namespace WebBotDetector
{
    class WebChecker
    {
        private static string ROOT_URI_BING = "https://api.datamarket.azure.com/Bing/Search";
        private static string API_KEY_BING = "Tf4VjUbeX8y0BMBiI7ivDopQ/oyctEdfeFSwh2c2nWI=";
        private static string API_KEY_GOOGLE = "AIzaSyAIhLJ9GyH70gQckMUKhKRniv5zoF_HCwE";
        private static string SEARCH_ENGINE_ID_GOOGLE = "013743414907371636293:lvz42rtmswi";

        public static long GetBingTotalResults(String query, Boolean exactResults)
        {
            var bingContainer = new Bing.BingSearchContainer(new Uri(ROOT_URI_BING));
            bingContainer.Credentials = new NetworkCredential(API_KEY_BING, API_KEY_BING);

            String queryString = query;
            if (exactResults) 
                queryString = "\"" + query + "\"";

            var imageQuery = bingContainer.Composite("web", queryString, null, null, null, null, null, null, null, null, null, null, null, null, null);
            var imageResults = imageQuery.Execute();

            var totalResults = imageResults.First().WebTotal;

            return totalResults == null ? 0 : totalResults.Value;
        }

        public static long GetGoogleTotalResults(String query, Boolean exactResults)
        {
            CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = API_KEY_GOOGLE });

            String queryString = query;
            if (exactResults)
                queryString = "\"" + query + "\"";

            Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(queryString);
            listRequest.Cx = SEARCH_ENGINE_ID_GOOGLE;
            Search search = listRequest.Execute();
            
            long? totalResults = search.SearchInformation.TotalResults;
            
            return totalResults == null ? 0 : totalResults.Value;
        }
    }
}
